package com.lebang.service;

import com.lebang.domain.AppSleepMemberRecord;
import com.lebang.example.AppSleepMemberRecordExample;
import com.lebang.mapper.AppSleepMemberRecordMapper;
import com.lebang.model.Whether;
import com.lebang.service.sys.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 睡觉赚
 *
 * @Author hwq
 * @Date 2020-01-10
 */
@Service
public class AppSleepService extends BaseService<AppSleepMemberRecord, Integer, AppSleepMemberRecordExample> {
    @Autowired
    private DictService dictService;

    @Autowired
    private AppSleepMemberRecordMapper baseMapper;


    /**
     * 开始睡觉
     *
     * @param memberId
     * @return
     */
    public int starSleep(String memberId) {
        AppSleepMemberRecord record = new AppSleepMemberRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setModifyTime(LocalDateTime.now());
        record.setHasDeleted(Whether.NO.getDbIndex());
        record.setMemberId(memberId);
        record.setCreateDate(LocalDate.now());
        record.setStarTime(System.currentTimeMillis());
        record.setLastTime(System.currentTimeMillis());
        record.setStatus(1);
        record.setClickCount(0);
        record.setAllPoint(0);
        this.insertModel(record);
        return record.getId();
    }

    public int last(AppSleepMemberRecord todayRecord, long time) {
        LocalDateTime dateTime = LocalDateTime.of(todayRecord.getCreateDate().minusDays(1), LocalTime.of(10, 0));
        //超过第二天十点不结算
        if (LocalDateTime.now().isBefore(dateTime)) {
            return 0;
        }
        Long minute = (todayRecord.getLastTime() - time) / 60000;
        if (minute <= 1) {
            return 0;
        }

        Integer point = dictService.selectIntByKeyName("sleep_minute_point") * minute.intValue();
        Integer maxPoint = dictService.selectIntByKeyName("sleep_max_point");
        Integer allPoint = todayRecord.getAllPoint() + point;
        if (allPoint >= maxPoint) {
            point = maxPoint - todayRecord.getAllPoint();
            allPoint = maxPoint;
        }
        todayRecord.setAllPoint(allPoint.intValue());
        todayRecord.setClickCount(todayRecord.getClickCount() + 1);
        todayRecord.setLastTime(System.currentTimeMillis());
        this.updateById(todayRecord);
        return point;
    }

    /**
     * 禁止领取奖励了
     * @param todayRecord
     */
    public void uniRecord(AppSleepMemberRecord todayRecord) {
        todayRecord.setStatus(0);
        this.updateById(todayRecord);
    }
}
